﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using HK2009.Common;
using HK2009.BusinessFacade;
using HK2009.BusinessFacadeHandler;
using HK2009.EntityQuery;
using System.Data.SqlClient;
using System.Text;

public partial class PurviewManage_RolesList : System.Web.UI.Page
{
    IRolePurviewHandler roleManage = new RolePurviewHandler();
    ISystemHandler sysManage = new SystemHandler();
    DataBase db = new DataBase();

    private static bool isUpdate = false;
    private static bool isDel = false;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //检查有没浏览该页面权限
            if (Session["UserID"] != null)
            {
                string strPermission = sysManage.GetLoginUserPermissions();
                if (!strPermission.Contains("1002"))
                {
                    Response.Redirect("~/NotPurview.aspx");
                    return;
                }
                else
                {
                    //判断用户有没有添加角色权限
                    if (strPermission.Contains("1003"))
                    {
                        lblRoleAdd.Visible = true;
                    }
                    else
                    {
                        lblRoleAdd.Visible = false;
                    }
                    //判断用户有没有修改角色权限
                    if (strPermission.Contains("1004"))
                    {
                        isUpdate = true;
                    }
                    else
                    {
                        isUpdate = false;
                    }
                    //判断用户有没有删除角色权限
                    if (strPermission.Contains("1005"))
                    {
                        isDel = true;
                    }
                    else
                    {
                        isDel = false;
                    }
                }
               // CheckPagePermission();//判断当前用户有没有添加删除更新的权限

            }         

            ViewState["OrderBy"] = "RoleID";
            ViewState["Accending"] = "asc";
            dataBind();
        }
    }


    /// <summary>
    /// 处理传入参数。。返回SQL条件和sqlparameter
    /// </summary>
    /// <param name="sqlstr"></param>
    /// <param name="parms"></param>
    private void ProcessParms(ref string sqlstr, ref SqlParameter[] parms)
    {
        int i = 0;
        sqlstr = "";
        if (ViewState["RoleName"] != null)
        {
            parms[0] = new SqlParameter("@RoleName", ViewState["RoleName"].ToString());
            sqlstr += " RoleName like '%' +  @RoleName + '%'";
        }
        else
        {
            parms[0] = new SqlParameter("@RoleID" + i.ToString(), "-1");
            sqlstr += " RoleID != @RoleID" + i.ToString();
            i += 1;
        }

        if (ViewState["RoleCode"] != null)
        {
            parms[1] = new SqlParameter("@RoleCode", ViewState["RoleCode"].ToString());
            sqlstr += " and RoleCode=@RoleCode";
        }
        else
        {
            parms[1] = new SqlParameter("@RoleID" + i.ToString(), "-1");
            sqlstr += " and RoleID!=@RoleID" + i.ToString();
        }
    }

    private void dataBind()
    {
        string sqlStr = "SELECT * FROM Roles where ";
        SqlParameter[] parms = new SqlParameter[2];
        string clause = string.Empty;
        ProcessParms(ref clause, ref parms);
        sqlStr += clause;

        DataTable dt = roleManage.GetRoleList(sqlStr, parms);
        DataView view = dt.DefaultView;
        view.Sort = ViewState["OrderBy"] + " " + ViewState["Accending"];
        grvList.DataSource = view;
        grvList.DataBind();
        if (dt != null && dt.Rows.Count > 0)
        {
            lblTotal.Text = dt.Rows.Count.ToString();
        }
        else
        {
            lblTotal.Text = "0";
        }
    }
  

    public string GetOperationName(object OperationIDs)
    {
        string name = string.Empty;
        if (OperationIDs != null && OperationIDs.ToString() != string.Empty)
        {
            string[] stroperationIDs = OperationIDs.ToString().Split(new char[] { ',' });
            for (int i = 0; i < stroperationIDs.Length; i++)
            {
                DataTable dt = roleManage.GetPurview(int.Parse(stroperationIDs[i]));
                if (dt != null && dt.Rows.Count > 0)
                {
                    name += dt.Rows[0]["PurviewName"].ToString() + ",";
                }
            }
            if (name != string.Empty)
            {
                name = name.Substring(0, name.Length - 1);
            }
        }
        return name;
    }

    protected void grvList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvList.PageIndex = e.NewPageIndex;
        dataBind();

    }
    protected void grvList_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "DelRole")
        {
            if (!roleManage.RoleDelete(int.Parse(e.CommandArgument.ToString())))
            {
                Jscript.AlertInAjax("删除角色失败!",UpdatePanel1);
            }
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (txtRoleName.Text.Trim() != string.Empty)
        {
            ViewState["RoleName"] = txtRoleName.Text.Trim();
        }
        else
        {
            ViewState["RoleName"] = null;
        }
        if (txtRoleCode.Text.Trim() != string.Empty)
        {
            ViewState["RoleCode"] = txtRoleCode.Text.Trim();
        }
        else
        {
            ViewState["RoleCode"] = null;
        }

        dataBind();
    }
    protected void grvList_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression.ToLower() == ViewState["OrderBy"].ToString().ToLower())
        {
            if (ViewState["Accending"].ToString().ToLower() == "asc")
            {
                ViewState["Accending"] = "desc";
            }
            else
            {
                ViewState["Accending"] = "asc";
            }
        }
        else
        {
            ViewState["OrderBy"] = e.SortExpression;
        }

        dataBind();
    }

    protected void ddlPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        grvList.PageSize = int.Parse(ddlPages.SelectedValue);
        dataBind();
    }
    protected void grvList_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton btnDel = (LinkButton)e.Row.FindControl("LinkButton1");           
            Label lblEdit = (Label)e.Row.FindControl("lblEdit");

            if (isUpdate)
            {
                lblEdit.Visible = true;
            }
            else
            {
                lblEdit.Visible = false;
            }

            if (isDel)
            {
                btnDel.Visible = true;
            }
            else
            {
                btnDel.Visible = false;
            }
        }

    }

    protected void lbtnGo_Click(object sender, EventArgs e)
    {
        TextBox txtPages = ((TextBox)grvList.BottomPagerRow.FindControl("txtPages"));
        try
        {
            int i = Convert.ToInt32(txtPages.Text) - 1;
            if (i >= 0 && i < grvList.PageCount)
            {
                this.grvList.PageIndex = i;
                //数据绑定
                dataBind();
            }
            else
            {
                Jscript.AlertInAjax("请输入大于0小于总页数的正整数!", UpdatePanel1);
                return;
            }
        }
        catch
        {
            Jscript.AlertInAjax("请输入大于0小于总页数的正整数!", UpdatePanel1);
        }
    }


    #region
    /// <summary>
    /// 判断当前用户有没有输入的权限
    /// </summary>
    /// <returns></returns>
    public void CheckPagePermission()
    {
        StringBuilder sb = new StringBuilder();
        bool istrue = false;
        IRolePurviewHandler userManage = new RolePurviewHandler();
        UsersQuery query = userManage.GetUsers(int.Parse(Session["UserID"].ToString()));
        if (query != null)
        {
            string roleIDs = query.Roles;
            if (roleIDs != string.Empty)
            {

                string strSql = "select * from Roles where RoleID in(" + roleIDs + ")";
                DataTable dtRoles = db.RunSql(strSql);
                if (dtRoles != null && dtRoles.Rows.Count > 0)
                {
                    for (int i = 0; i < dtRoles.Rows.Count; i++)
                    {
                        sb.Append(dtRoles.Rows[i]["RolePurview"].ToString() + ",");
                    }
                }

                string permission = sb.ToString();
                if (permission.Length > 0)
                {
                    permission = permission.Substring(0, permission.Length - 1);


                    //判断用户有没有添加角色权限
                    if (permission.Contains("1003"))
                    {
                        lblRoleAdd.Visible = true;
                    }
                    else
                    {
                        lblRoleAdd.Visible = false;
                    }
                    //判断用户有没有修改角色权限
                    if (permission.Contains("1004"))
                    {
                        isUpdate = true;
                    }
                    else
                    {
                        isUpdate = false;
                    }
                    //判断用户有没有删除角色权限
                    if (permission.Contains("1005"))
                    {
                        isDel = true;
                    }
                    else
                    {
                        isDel = false;
                    }
                }
            }
        }

    }
    #endregion

}
